package com.gc.controller;

import com.gc.common.constants.FileConstants;
import com.gc.common.resp.ApiResult;
import com.gc.pojo.SysTemplate;
import com.gc.pojo.SysUser;
import com.gc.services.TemplateService;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("template")
public class TemplateController {

    @Autowired
    private TemplateService templateService;

    @GetMapping("download")
    public String down(@RequestParam Integer tid, HttpServletResponse response) {
        //todo 查询一下报告编号...
        String downloadFilePath = "D:/images/";
        //todo 查询一下模板path
        String fileName = "3P4W.jpg";
        File file = new File(downloadFilePath + fileName);
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + tid + "_" + fileName);// 设置文件名
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @GetMapping("submit-view")
    public ModelAndView submit_view(){
        ModelAndView mav = new ModelAndView("template/submit-list");
        return mav;
    }

    @PostMapping("submit")
    @ResponseBody
    public ApiResult submit(@RequestParam("file")MultipartFile file,String templateName,String remark){
        ApiResult result = new ApiResult();
        if (file.isEmpty()) {
            return new ApiResult(200,"文件不能为空！");
        }
        long tm = System.currentTimeMillis();
        int lastIndexOf = file.getOriginalFilename().lastIndexOf(".");
        String suffix = file.getOriginalFilename().substring(lastIndexOf);
        String filename = tm+suffix;
        try {
            File localFile = new File(FileConstants.TEMPLATE_LOCAL_URL + filename);
            if(localFile.exists()){
                return new ApiResult(500,"文件已存在！(文件名有重复)");
            }
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
            return new ApiResult(500,"文件上传失败！");
        }
        SysUser curUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
        SysTemplate template = new SysTemplate();
        template.setCreateTime(new Date());
        template.setCreateBy(curUser.getUserId());
        template.setPath(FileConstants.TEMPLATE_VIRTUAL_URL+filename);
        template.setRemark(remark);
        template.setTemplateName(templateName);
        int count = templateService.addTemplate(template);
        if(count != 1){
            //todo 上传失败时 删除文件
            return new ApiResult(500,"模板数据上传失败！");
        }
        return result;
    }

    @PostMapping("remove")
    @ResponseBody
    public ApiResult remove(@RequestParam Integer tid){
        //todo tid 为1 不能删
        ApiResult result = new ApiResult();
        SysTemplate template = templateService.getTemplateByTId(tid);
        String varPath = template.getPath();  //这只是虚拟路径 , 获取文件名
        int lastIndexOf = varPath.lastIndexOf("/") + 1;
        String locPath = varPath.substring(lastIndexOf);//获取到文件名
        File file = new File(FileConstants.TEMPLATE_LOCAL_URL + locPath);
        if (file.exists()) {
            file.delete();
        }
        int count = templateService.removeTemplateByTId(tid);
        return result;
    }


    @GetMapping("getList")
    @ResponseBody
    public List<SysTemplate> getList(){
        List<SysTemplate> list = templateService.getAll();
        return list;
    }

    @GetMapping("get")
    @ResponseBody
    public SysTemplate get(@RequestParam Integer tid){
        SysTemplate template = templateService.getTemplateByTId(tid);
        return template;
    }
}
